package org.example.car.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.car.service.domain.Battery;
import org.example.car.service.service.BatteryService;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: Yanyanyu
 * @Date: 2024/6/30 15:34
 */
@Slf4j
public class BatteryListener implements ReadListener<Battery> {

    private static final int BATCH_COUNT = 3;

    private List<Battery> batteryList= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private BatteryService batteryService;

    public BatteryListener(BatteryService batteryService){
        this.batteryService=batteryService;
    }



    @Override
    public void invoke(Battery battery, AnalysisContext analysisContext) {
        System.out.println("解析的数据："+battery);

        batteryList.add(battery);

        if(batteryList.size()>BATCH_COUNT){

            batteryService.insertAll(batteryList);

            batteryList=ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完成");
        if(batteryList.size()>0){
            batteryService.insertAll(batteryList);
        }
    }
}
